import hashlib

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView



class GetTestApiView(APIView):
    def get(self, request):
        pyload = {
            "Django": "Django2.1"
        }
        return Response(pyload)


class WeiXinApiView(APIView):
    """
    NFO basehttp 124 "GET /wx?signature=22b0d58bb3d12410a5e08bbc858e15e523a1448d&echostr=7508373374110726071&timestamp=1544171909&nonce=307958945
    """

    def get(self, request):
        # 获取关键参数
        data = request.query_params.dict()
        if len(data) == 0:
            return "hello, this is handle view"
        # 提取出字段
        signature = request.GET.get("signature", None)
        timestamp = request.GET.get("timestamp", None)
        nonce = request.GET.get("nonce", None)
        echostr = request.GET.get('echostr', None)
        print(signature)
        token = "tangxx"  # 请按照公众平台官网\基本配置中信息填写
        list = [token, timestamp, nonce]
        list.sort()
        sha1 = hashlib.sha1()
        list = ''.join(list)
        sha1.update(list.encode('utf-8'))
        hashcode = sha1.hexdigest()
        print("handle/GET func: hashcode, signature: ", hashcode, signature)

        # 如果hashcode与signature相等，确定该数据源是微信后台，返回echostr，供微信后台认证token
        if hashcode == signature:
            return HttpResponse(echostr)
        else:
            # 不作处理，返回""
            return HttpResponse("")

